/*******************************************************************************
 * Copyright (c) 2000, 2004 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Common Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v10.html
 * 
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
module dwt.graphics.fontdata;


private import dwt.dwt;



private import dwt.graphics.color;
private import dwt.graphics.cursor;
private import dwt.graphics.device;
private import dwt.graphics.devicedata;
private import dwt.graphics.drawable;
private import dwt.graphics.font;
private import dwt.graphics.fontmetrics;
private import dwt.graphics.gc;
private import dwt.graphics.gcdata;
private import dwt.graphics.image;
private import dwt.graphics.imagedata;
private import dwt.graphics.imageloader;
private import dwt.graphics.imageloaderevent;
private import dwt.graphics.imageloaderlistener;
private import dwt.graphics.palettedata;
private import dwt.graphics.point;
private import dwt.graphics.rectangle;
private import dwt.graphics.region;
private import dwt.graphics.rgb;
private import dwt.graphics.textlayout;
private import dwt.graphics.textstyle;
private import dwt.internal.bidiutil;
private import dwt.internal.cloneablecompatibility;
private import dwt.internal.compatibility;
private import dwt.internal.library;
private import dwt.internal.serializablecompatibility;
private import dwt.internal.dwteventlistener;
private import dwt.internal.dwteventobject;
private import dwt.internal.win32.os;



private import dwt.util.javatypes;
private import dwt.util.util;
private import dwt.util.vector;
private import dwt.util.hashtable;
private import dwt.util.eventhandler;



/**
 * Instances of this class describe operating system fonts.
 * <p>
 * For platform-independent behaviour, use the get and set methods
 * corresponding to the following properties:
 * <dl>
 * <dt>height</dt><dd>the height of the font in points</dd>
 * <dt>name</dt><dd>the face name of the font, which may include the foundry</dd>
 * <dt>style</dt><dd>A bitwise combination of NORMAL, ITALIC and BOLD</dd>
 * </dl>
 * If extra, platform-dependent functionality is required:
 * <ul>
 * <li>On <em>Windows</em>, the data member of the <code>FontData</code>
 * corresponds to a Windows <code>LOGFONT</code> structure whose fields
 * may be retrieved and modified.</li>
 * <li>On <em>X</em>, the fields of the <code>FontData</code> correspond
 * to the entries in the font's XLFD name and may be retrieved and modified.
 * </ul>
 * Application code does <em>not</em> need to explicitly release the
 * resources managed by each instance when those instances are no longer
 * required, and thus no <code>dispose()</code> method is provided.
 *
 * @see Font
 */

public class FontData {
	
	/**
	 * A Win32 LOGFONT struct
	 * (Warning: This field is platform dependent)
	 */
	// <Shawn> declared as a struct instead a reference 
	public LOGFONT data;
	
	/**
	 * The height of the font data in points
	 * (Warning: This field is platform dependent)
	 */
	public int height;
	
	/**
	 * The locales of the font
	 * (Warning: These fields are platform dependent)
	 */
	char[] lang, country, variant;

	private static FontData s_this;
	
/**	 
 * Constructs a new un-initialized font data.
 */
public this() {
	// We set the charset field so that
	// wildcard searching will work properly
	// out of the box
	data.lfCharSet = cast(BYTE)OS.DEFAULT_CHARSET;
	height = 12;
}

/**
 * Constructs a new font data given the Windows <code>LOGFONT</code>
 * that it should represent.
 * 
 * @param data the <code>LOGFONT</code> for the result
 */
this(LOGFONT* data, int height) {
	// copy the content of the LOGFONT
	this.data = *data;
	this.height = height;
}

/**
 * Constructs a new FontData given a string representation
 * in the form generated by the <code>FontData.toString</code>
 * method.
 * <p>
 * Note that the representation varies between platforms,
 * and a FontData can only be created from a string that was 
 * generated on the same platform.
 * </p>
 *
 * @param string the string representation of a <code>FontData</code> (must not be null)
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - if the argument is null</li>
 *    <li>ERROR_INVALID_ARGUMENT - if the argument does not represent a valid description</li>
 * </ul>
 *
 * @see #toString
 */
public this(char[] string) {
	if (string is null) DWT.error(__FILE__, __LINE__, DWT.ERROR_NULL_ARGUMENT);
	int start = 0;
	int end = Converter.indexOf(string, '|');
	if (end == -1) DWT.error(__FILE__, __LINE__, DWT.ERROR_INVALID_ARGUMENT);
	char[] version_ren1 = Converter.substring(string, start, end);
	try {
		if (Integer.parseInt(version_ren1[]) != 1) DWT.error(__FILE__, __LINE__, DWT.ERROR_INVALID_ARGUMENT); 
	} catch (Exception e) {
		DWT.error(__FILE__, __LINE__, DWT.ERROR_INVALID_ARGUMENT);
	}
	
	start = end + 1;
	end = Converter.indexOf(string, '|', start);
	if (end == -1) DWT.error(__FILE__, __LINE__, DWT.ERROR_INVALID_ARGUMENT);
	char[] name = Converter.substring(string, start, end);
	
	start = end + 1;
	end = Converter.indexOf(string, '|', start);
	if (end == -1) DWT.error(__FILE__, __LINE__, DWT.ERROR_INVALID_ARGUMENT);
	int height = 0;
	try {
		height = Integer.parseInt(Converter.substring(string, start,end)[]);
	} catch (Exception e) {
		DWT.error(__FILE__, __LINE__, DWT.ERROR_INVALID_ARGUMENT);
	}
	
	start = end + 1;
	end = Converter.indexOf(string, '|', start);
	if (end == -1) DWT.error(__FILE__, __LINE__, DWT.ERROR_INVALID_ARGUMENT);
	int style = 0;
	try {
		style = Integer.parseInt(Converter.substring(string, start, end)[]);
	} catch (Exception e) {
		DWT.error(__FILE__, __LINE__, DWT.ERROR_INVALID_ARGUMENT);
	}

	start = end + 1;
	end = Converter.indexOf(string, '|', start);
//	data = new LOGFONT();
	data.lfCharSet = cast(BYTE)OS.DEFAULT_CHARSET;
	setName(name);
	setHeight(height);
	setStyle(style);
	if (end == -1) return;
	char[] platform = Converter.substring(string, start, end);

	start = end + 1;
	end = Converter.indexOf(string, '|', start);
	if (end == -1) return;
	char[] version_ren2 = Converter.substring(string, start, end);

	if ((platform == ("WINDOWS")) && (version_ren2 == ("1"))) {
		LOGFONT* newData = &data;
		try {
			start = end + 1;
			end = Converter.indexOf(string, '|', start);
			if (end == -1) return;
			newData.lfHeight = Integer.parseInt(Converter.substring(string, start, end)[]);
			start = end + 1;
			end = Converter.indexOf(string, '|', start);
			if (end == -1) return;
			newData.lfWidth = Integer.parseInt(Converter.substring(string, start, end)[]);
			start = end + 1;
			end = Converter.indexOf(string, '|', start);
			if (end == -1) return;
			newData.lfEscapement = Integer.parseInt(Converter.substring(string, start, end)[]);
			start = end + 1;
			end = Converter.indexOf(string, '|', start);
			if (end == -1) return;
			newData.lfOrientation = Integer.parseInt(Converter.substring(string, start, end)[]);
			start = end + 1;
			end = Converter.indexOf(string, '|', start);
			if (end == -1) return;
			newData.lfWeight = Integer.parseInt(Converter.substring(string, start, end)[]);
			start = end + 1;
			end = Converter.indexOf(string, '|', start);
			if (end == -1) return;
			newData.lfItalic = cast(BYTE)(Integer.parseInt(Converter.substring(string, start, end)[]));
			start = end + 1;
			end = Converter.indexOf(string, '|', start);
			if (end == -1) return;
			newData.lfUnderline = cast(BYTE)(Integer.parseInt(Converter.substring(string, start, end)[]));
			start = end + 1;
			end = Converter.indexOf(string, '|', start);
			if (end == -1) return;
			newData.lfStrikeOut = cast(BYTE)(Integer.parseInt(Converter.substring(string, start, end)[]));
			start = end + 1;
			end = Converter.indexOf(string, '|', start);
			if (end == -1) return;
			newData.lfCharSet = cast(BYTE)(Integer.parseInt(Converter.substring(string, start, end)[]));
			start = end + 1;
			end = Converter.indexOf(string, '|', start);
			if (end == -1) return;
			newData.lfOutPrecision = cast(BYTE)(Integer.parseInt(Converter.substring(string, start, end)[]));
			start = end + 1;
			end = Converter.indexOf(string, '|', start);
			if (end == -1) return;
			newData.lfClipPrecision = cast(BYTE)(Integer.parseInt(Converter.substring(string, start, end)[]));
			start = end + 1;
			end = Converter.indexOf(string, '|', start);
			if (end == -1) return;
			newData.lfQuality = cast(BYTE)(Integer.parseInt(Converter.substring(string, start, end)[]));
			start = end + 1;
			end = Converter.indexOf(string, '|', start);
			if (end == -1) return;
			newData.lfPitchAndFamily = cast(BYTE)(Integer.parseInt(Converter.substring(string, start, end)[]));
			start = end + 1;
		} catch (Exception e) {
			setName(name);
			setHeight(height);
			setStyle(style);
			return;
		}
		char[] buffer = Converter.substring(string, start);
		int len = Math.min(OS.LF_FACESIZE - 1, buffer.length);
		newData.lfFaceName[0..len] = Converter.StrToTCHARs(buffer)[0..len];				
//		data = newData;
	}
}

/**	 
 * Constructs a new font data given a font name,
 * the height of the desired font in points, 
 * and a font style.
 *
 * @param name the name of the font (must not be null)
 * @param height the font height in points
 * @param style a bit or combination of NORMAL, BOLD, ITALIC
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - when the font name is null</li>
 *    <li>ERROR_INVALID_ARGUMENT - if the height is negative</li>
 * </ul>
 */
public this(char[] name, int height, int style) {
	if (name is null) DWT.error(__FILE__, __LINE__, DWT.ERROR_NULL_ARGUMENT);
//	data = new LOGFONT();
	setName(name);
	setHeight(height);
	setStyle(style);
	// We set the charset field so that
	// wildcard searching will work properly
	// out of the box
	data.lfCharSet = cast(BYTE)OS.DEFAULT_CHARSET;
}

/**
 * Compares the argument to the receiver, and returns true
 * if they represent the <em>same</em> object using a class
 * specific comparison.
 *
 * @param object the object to compare with this object
 * @return <code>true</code> if the object is the same as this object and <code>false</code> otherwise
 *
 * @see #hashCode
 */
public boolean equals (Object object) {
	if (object is this) return true;
	if (!(cast(FontData)object)) return false;
	FontData fd = cast(FontData)object;
	LOGFONT* lf = &fd.data;
	return data.lfCharSet == lf.lfCharSet &&
		/*
		* This code is intentionally commented.  When creating
		* a FontData, lfHeight is not necessarily set.  Instead
		* we check the height field which is always set.
		*/ 
//		data.lfHeight == lf.lfHeight &&
		height == fd.height &&
		data.lfWidth == lf.lfWidth &&
		data.lfEscapement == lf.lfEscapement &&
		data.lfOrientation == lf.lfOrientation &&
		data.lfWeight == lf.lfWeight &&
		data.lfItalic == lf.lfItalic &&
		data.lfUnderline == lf.lfUnderline &&
		data.lfStrikeOut == lf.lfStrikeOut &&
		data.lfCharSet == lf.lfCharSet &&
		data.lfOutPrecision == lf.lfOutPrecision &&
		data.lfClipPrecision == lf.lfClipPrecision &&
		data.lfQuality == lf.lfQuality &&
		data.lfPitchAndFamily == lf.lfPitchAndFamily &&
		getName() == (fd.getName());
}

extern (Windows) static 
int EnumLocalesProc(TCHAR* lpLocaleString) {

	/* Get the locale ID */
	int _length = 8;
	char[] str = Converter.TCHARzToStr(lpLocaleString, _length);
	int lcid = Integer.parseInt(str, 16);

	TCHAR[] buffer = new TCHAR[_length];

	/* Check the language */
	int size = OS.GetLocaleInfo(lcid, OS.LOCALE_SISO639LANGNAME, buffer.ptr, _length);
	if (size <= 0 || s_this.lang != (Converter.substring(Converter.TCHARzToStr(buffer.ptr), 0, size - 1))) return 1;

	/* Check the country */
	if (s_this.country !is null) {
		size = OS.GetLocaleInfo(lcid, OS.LOCALE_SISO3166CTRYNAME, buffer.ptr, _length);
		if (size <= 0 || s_this.country != (Converter.substring(Converter.TCHARzToStr(buffer.ptr), 0, size - 1))) return 1;
	}

	/* Get the charset */
	size = OS.GetLocaleInfo(lcid, OS.LOCALE_IDEFAULTANSICODEPAGE, buffer.ptr, _length);
	if (size <= 0) return 1;
	int cp = Integer.parseInt(Converter.substring(Converter.TCHARzToStr(buffer.ptr), 0, size - 1)[]);
	CHARSETINFO lpCs;
	OS.TranslateCharsetInfo(cast(DWORD*)cp, &lpCs, OS.TCI_SRCCODEPAGE);
	s_this.data.lfCharSet = cast(BYTE)lpCs.ciCharset;

	return 0;
}

/**
 * Returns the height of the receiver in points.
 *
 * @return the height of this FontData
 *
 * @see #setHeight
 */
public int getHeight() {
	return height;
}

/**
 * Returns the locale of the receiver.
 * <p>
 * The locale determines which platform character set this
 * font is going to use. Widgets and graphics operations that
 * use this font will convert UNICODE strings to the platform
 * character set of the specified locale.
 * </p>
 * <p>
 * On platforms where there are multiple character sets for a
 * given language/country locale, the variant portion of the
 * locale will determine the character set.
 * </p>
 * 
 * @return the <code>String</code> representing a Locale object
 * @since 3.0
 */
public char[] getLocale () {
	char[] buffer;
	char sep = '_';
	if (lang !is null) {
		_append(buffer, lang);
		_append(buffer, sep);
	}
	if (country !is null) {
		_append(buffer, country);
		_append(buffer, sep);
	}
	if (variant !is null) {
		_append(buffer, variant);
	}
	
	char[] result = buffer;
	int len = result.length;
	if (len > 0) {
		if (result[len - 1] == sep) {
			result = Converter.substring(result, 0, len - 1);
		}
	} 
	return result;
}

/**
 * Returns the name of the receiver.
 * On platforms that support font foundries, the return value will
 * be the foundry followed by a dash ("-") followed by the face name.
 *
 * @return the name of this <code>FontData</code>
 *
 * @see #setName
 */
public char[] getName() {
	TCHAR[] chars = data.lfFaceName;
	return Converter.TCHARzToStr(cast(TCHAR*)chars, -1);
}

/**
 * Returns the style of the receiver which is a bitwise OR of 
 * one or more of the <code>DWT</code> constants NORMAL, BOLD
 * and ITALIC.
 *
 * @return the style of this <code>FontData</code>
 * 
 * @see #setStyle
 */
public int getStyle() {
	int style = DWT.NORMAL;
	if (data.lfWeight == 700) style |= DWT.BOLD;
	if (data.lfItalic != 0) style |= DWT.ITALIC;
	return style;
}

/**
 * Returns an integer hash code for the receiver. Any two 
 * objects which return <code>true</code> when passed to 
 * <code>equals</code> must return the same value for this
 * method.
 *
 * @return the receiver's hash
 *
 * @see #equals
 */
public int hashCode () {
	return data.lfCharSet ^ height ^ data.lfWidth ^ data.lfEscapement ^
		data.lfOrientation ^ data.lfWeight ^ data.lfItalic ^data.lfUnderline ^
		data.lfStrikeOut ^ data.lfCharSet ^ data.lfOutPrecision ^
		data.lfClipPrecision ^ data.lfQuality ^ data.lfPitchAndFamily
		;
		// TODO:
		//^
		//(getName().toHash());
}

/**
 * Sets the height of the receiver. The parameter is
 * specified in terms of points, where a point is one
 * seventy-second of an inch.
 *
 * @param height the height of the <code>FontData</code>
 *
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_INVALID_ARGUMENT - if the height is negative</li>
 * </ul>
 * 
 * @see #getHeight
 */
public void setHeight(int height) {
	if (height < 0) DWT.error(__FILE__, __LINE__, DWT.ERROR_INVALID_ARGUMENT);
	this.height = height;
}

/**
 * Sets the locale of the receiver.
 * <p>
 * The locale determines which platform character set this
 * font is going to use. Widgets and graphics operations that
 * use this font will convert UNICODE strings to the platform
 * character set of the specified locale.
 * </p>
 * <p>
 * On platforms where there are multiple character sets for a
 * given language/country locale, the variant portion of the
 * locale will determine the character set.
 * </p>
 * 
 * @param locale the <code>String</code> representing a Locale object
 * @see java.util.Locale#toString
 */
public void setLocale(char[] locale) {	
	lang = country = variant = null;
	if (locale !is null) {
		char sep = '_';
		int length = locale.length;
		int firstSep, secondSep;
		
		firstSep = Converter.indexOf(locale, sep);
		if (firstSep == -1) {
			firstSep = secondSep = length;
		} else {
			secondSep = Converter.indexOf(locale, sep, firstSep + 1);
			if (secondSep == -1) secondSep = length;
		}
		if (firstSep > 0) lang = Converter.substring(locale, 0, firstSep);
		if (secondSep > firstSep + 1) country = Converter.substring(locale, firstSep + 1, secondSep);
		if (length > secondSep + 1) variant = Converter.substring(locale, secondSep + 1);
	}
	if (lang is null) {
		data.lfCharSet = cast(BYTE)OS.DEFAULT_CHARSET;
	} else {
		s_this = this;
		OS.EnumSystemLocales(&EnumLocalesProc, OS.LCID_SUPPORTED);
		s_this = null;
	}
}

/**
 * Sets the name of the receiver.
 * <p>
 * Some platforms support font foundries. On these platforms, the name
 * of the font specified in setName() may have one of the following forms:
 * <ol>
 * <li>a face name (for example, "courier")</li>
 * <li>a foundry followed by a dash ("-") followed by a face name (for example, "adobe-courier")</li>
 * </ol>
 * In either case, the name returned from getName() will include the
 * foundry.
 * </p>
 * <p>
 * On platforms that do not support font foundries, only the face name
 * (for example, "courier") is used in <code>setName()</code> and 
 * <code>getName()</code>.
 * </p>
 *
 * @param name the name of the font data (must not be null)
 * @exception IllegalArgumentException <ul>
 *    <li>ERROR_NULL_ARGUMENT - when the font name is null</li>
 * </ul>
 *
 * @see #getName
 */
public void setName(char[] name) {
	if (name is null) DWT.error(__FILE__, __LINE__, DWT.ERROR_NULL_ARGUMENT);

	/* The field lfFaceName must be NULL terminated */
	int len = Math.min(OS.LF_FACESIZE - 1, name.length);
	
	data.lfFaceName[0..len] = Converter.StrToTCHARs(name)[0..len];
	data.lfFaceName[len] = 0;
}

/**
 * Sets the style of the receiver to the argument which must
 * be a bitwise OR of one or more of the <code>DWT</code> 
 * constants NORMAL, BOLD and ITALIC.
 *
 * @param style the new style for this <code>FontData</code>
 *
 * @see #getStyle
 */
public void setStyle(int style) {
	if ((style & DWT.BOLD) == DWT.BOLD) {
		data.lfWeight = 700;
	} else {
		data.lfWeight = 0;
	}
	if ((style & DWT.ITALIC) == DWT.ITALIC) {
		data.lfItalic = 1;
	} else {
		data.lfItalic = 0;
	}
}

/**
 * Returns a string representation of the receiver which is suitable
 * for constructing an equivalent instance using the 
 * <code>FontData(String)</code> constructor.
 *
 * @return a string representation of the FontData
 *
 * @see FontData
 */
 private void _append(inout char[] sc, char[] val) { sc ~= val; }
 private void _append(inout char[] sc, int val) { sc ~= Int.toString(val); }
 public char[] toString() {
 	
	char[] buffer = "";
	_append(buffer, "1|");
	_append(buffer, getName());
	_append(buffer, "|");
	_append(buffer, getHeight());
	_append(buffer, "|");
	_append(buffer, getStyle());
	_append(buffer, "|");
	_append(buffer, "WINDOWS|1|");	
	_append(buffer, data.lfHeight);
	_append(buffer, "|");
	_append(buffer, data.lfWidth);    
	_append(buffer, "|");
	_append(buffer, data.lfEscapement); 
	_append(buffer, "|");
	_append(buffer, data.lfOrientation);    
	_append(buffer, "|");
	_append(buffer, data.lfWeight);    
	_append(buffer, "|");
	_append(buffer, data.lfItalic);    
	_append(buffer, "|");
	_append(buffer, data.lfUnderline); 
	_append(buffer, "|");
	_append(buffer, data.lfStrikeOut);    
	_append(buffer, "|");
	_append(buffer, data.lfCharSet);    
	_append(buffer, "|");
	_append(buffer, data.lfOutPrecision); 
	_append(buffer, "|");
	_append(buffer, data.lfClipPrecision);    
	_append(buffer, "|");
	_append(buffer, data.lfQuality);    
	_append(buffer, "|");
	_append(buffer, data.lfPitchAndFamily);
	_append(buffer, "|");
	_append(buffer, getName());
	return buffer;
}

/**	 
 * Invokes platform specific functionality to allocate a new font data.
 * <p>
 * <b>IMPORTANT:</b> This method is <em>not</em> part of the public
 * API for <code>FontData</code>. It is marked public only so that
 * it can be shared within the packages provided by DWT. It is not
 * available on all platforms, and should never be called from
 * application code.
 * </p>
 *
 * @param data the <code>LOGFONT</code> for the font data
 * @param height the height of the font data
 * @return a new font data object containing the specified <code>LOGFONT</code> and height
 */
public static FontData win32_new(LOGFONT* data, int height) {
	return new FontData(data, height);
}

}
